import datetime
import sys

import psycopg2


class DbOperate:
    def __init__(self, **dbinfo):
        self.db_info = dbinfo
        self.conn = None
        self.cur = None

    def conn_db(self):
        self.conn = psycopg2.connect(database=self.db_info['db_name'],
                                     user=self.db_info['db_user'],
                                     password=self.db_info['db_password'],
                                     host=self.db_info['db_host'],
                                     port=self.db_info['port'])
        self.conn.set_client_encoding('utf-8')
        self.cur = self.conn.cursor()
        print("connect successful")

    def exec_dml_sql(self, sql_cmd):
        self.cur.execute(sql_cmd)
        self.conn.commit()
        print("dml operate successful")

    def exec_dql_sql(self, sql_cmd):
        self.cur.execute(sql_cmd)
        rows = self.cur.fetchall()
        print("select successful")
        return rows

    def close_conn(self):
        self.conn.close()
        print("close connect successful")


class Resource:
    def __init__(self, filename):
        self.filename = filename
        self.cpu_res = {}

    def get_cpu(self, line):
        if len(line) <= 1:
            return
        cpu_name = line.split()[0][1:]
        if cpu_name not in self.cpu_res:
            split_line = re.split(r"[,\s]+", line)
            cpu_us = float(split_line[2])
            cpu_sy = float(split_line[4]) + float(split_line[14])
            self.cpu_res[cpu_name] = [round(cpu_us, 1), round(cpu_sy, 1)]
        else:
            new_split = re.split(r"[,\s]+", line)
            new_us = float(new_split[2])
            new_sy = float(new_split[4]) + float(new_split[14])
            self.cpu_res[cpu_name][0] = round(self.cpu_res[cpu_name][0]
                                        + new_us, 1)
            self.cpu_res[cpu_name][1] = round(self.cpu_res[cpu_name][1]
                                        + new_sy, 1)

    def get_resource(self):
        with open(self.filename) as file:
            for line in file:
                line_content = line.strip()
                if line_content.startswith("%Cpu"):
                    self.get_cpu(line_content)

        for each_res in self.cpu_res.values():
            each_res[0] = round(each_res[0] / 3, 1)
            each_res[1] = round(each_res[1] / 3, 1)

        return self.cpu_res


if __name__ == '__main__':
    Usage = "Usage:input as " \
            "'python3 perf_in_db.py cpu_feature HA t_feature tpmc' "
    if len(sys.argv) < 4:
        print(Usage)
        exit(0)

    cpu_feature = sys.argv[1]
    HA = sys.argv[2]
    t_feature = sys.argv[3]
    tpmc = sys.argv[4]

    if len(sys.argv) == 5:
        resource_file = sys.argv[5]
        rsc = Resource(resource_file)

    db_info = {'db_name': '',
               'db_user': '',
               'db_password': '',
               'db_host': '',
               'port': ''}
    my_db = DbOperate(**db_info)
    my_db.conn_db()
    start_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print('删除一月前数据')
    cmd = f'delete from "ReportApp_perfinfo" ' \
        f'where start_time < to_timestamp(substring(to_char(' \
        f'now(), \'yyyy-MM-DD hh24:MI:ss\') ' \
        f'from 1 for 10), \'yyyy-MM-dd\') - ' \
        f'interval \'30d\';'
    my_db.exec_dml_sql(cmd)

    print('新值入库')
    cmd = f'insert into "ReportApp_perfinfo"(' \
        f'cpu_feature, "cluster", t_feature, start_time, tpmc) values (' \
        f'\'{cpu_feature}\', ' \
        f'\'{HA}\', ' \
        f'\'{t_feature}\', ' \
        f'\'{start_time}\', ' \
        f'\'{tpmc}\');'
    my_db.exec_dml_sql(cmd)

    if len(sys.argv) == 5:
        cmd = f'delete from "ReportApp_perfCPU" ' \
              f'where start_time < to_timestamp(substring(to_char(' \
              f'now(), \'yyyy-MM-DD hh24:MI:ss\') ' \
              f'from 1 for 10), \'yyyy-MM-dd\') - ' \
              f'interval \'30d\';'
        y_db.exec_dml_sql(cmd)

        cpu_res = rsc.get_resource()
        for core, res in cpu_res.items():
            cmd = f'insert into "ReportApp_perfCPU"(' \
            f'cpu_core, us, sy, start_time) values (' \
            f'\'{core}\', \'{res[0]}\', \'{res[1]}\', ' \
            f'\'{start_time}\');'
            y_db.exec_dml_sql(cmd)
    my_db.close_conn()
